package com.example.rbacmanage.controller.background;

import com.example.rbacmanage.common.Result;
import com.example.rbacmanage.service.system.FileUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * 文件上传控制器
 * 处理文件上传相关的请求
 */
@RestController
@RequestMapping("/background/file")
public class FileUploadController {

    @Autowired
    private FileUploadService fileUploadService;

    /**
     * 上传文件块
     *
     * @param chunk       文件块
     * @param chunkNumber 当前块的编号
     * @param md5         文件的MD5值
     * @return 上传结果
     */
    @PostMapping("/upload")
    public Result uploadChunk(
            @RequestParam("chunk") MultipartFile chunk,
            @RequestParam("chunkNumber") int chunkNumber,
            @RequestParam("md5") String md5) {
        try {
            fileUploadService.uploadChunk(chunk, chunkNumber, md5);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }


    /**
     * 检查文件是否已上传
     *
     * @param md5 文件的MD5值
     * @return 已上传的文件块编号
     */
    @GetMapping("/check/{md5}")
    public Result checkFile(@PathVariable String md5) {
        Set<Integer> uploadedChunks = fileUploadService.getUploadedChunks(md5);
        return Result.success(uploadedChunks.stream()
                .map(String::valueOf)
                .collect(Collectors.joining(":")));
    }


    /**
     * 合并文件块
     *
     * @param md5     文件的MD5值
     * @param fileName 文件名
     * @return 合并结果
     */
    @PostMapping("/merge")
    public Result mergeChunks(@RequestParam("md5") String md5, @RequestParam("fileName") String fileName) {
        try {
            return Result.success(fileUploadService.mergeChunks(md5, fileName));
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}